{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a11fa1b9-d002-4177-8f49-4130a3598995",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "cc8f9970-72e0-4aac-8798-e3290696efff",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BernoulliBandit:\n",
    "    # 伯努利老虎机，输入K表示拉杆个数\n",
    "    def __init__(self,K):\n",
    "        self.probs =np.random.uniform(size=K) #随机生成K个0~1的数，作为拉动每根拉杆的获奖概率\n",
    "        self.best_idx = np.argmax(self.probs) #获奖概率最大的拉杆\n",
    "        self.best_prob = self.probs[self.best_idx] # 最大的获奖概率\n",
    "        self.K = K\n",
    "\n",
    "\n",
    "    def step(self,k):\n",
    "        #当玩家选择了k号拉杆后，根据拉动该老虎机的k号拉杆获得奖励的概率返回1（获奖）或0（未获奖）\n",
    "        if np.random.rand() < self.probs[k]:\n",
    "            return 1\n",
    "        else:\n",
    "            return 0\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3b2773f9-67f7-4920-ac83-c7f4f5fb101d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "获奖概率最大的拉杆为1号,其获奖概率为0.9507\n"
     ]
    }
   ],
   "source": [
    "np.random.seed(42)\n",
    "K = 10\n",
    "bandit_10_arm = BernoulliBandit(K)\n",
    "print(\"获奖概率最大的拉杆为%d号,其获奖概率为%.4f\" %\n",
    "      (bandit_10_arm.best_idx, bandit_10_arm.best_prob))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ed1cdff-3066-4911-911e-8865e4dca75a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
